package cn.com.taiji.pos.controller;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.pos.common.util.MD5;
import cn.com.taiji.pos.common.util.pay.alipay.zhifubao.model.builder.AlipayTradeRefundRequestBuilder;
import cn.com.taiji.pos.common.util.pay.alipay.zhifubao.model.result.AlipayF2FRefundResult;
import cn.com.taiji.pos.common.util.pay.alipay.zhifubao.service.AlipayTradeService;
import cn.com.taiji.pos.common.util.pay.alipay.zhifubao.service.impl.AlipayTradeServiceImpl;
import cn.com.taiji.pos.common.util.pay.wxpay.WXPay;
import cn.com.taiji.pos.common.util.pay.wxpay.WXPayConfigImpl;
import cn.com.taiji.pos.entity.*;
import cn.com.taiji.pos.service.*;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@RestController
@RequestMapping("/RetreatFood")
public class RetreatFoodController {
    @Value("${CARD_ACCOUNT_TYPE_CHUZHI}")
    private String CARD_ACCOUNT_TYPE_CHUZHI;
    @Value("${SETTLEMENT_TYPE_ID_YuShouKaJi}")
    private String SETTLEMENT_TYPE_ID_YuShouKaJi;
    @Value("${SETTLEMENT_TYPE_ID_YingShouKaJi}")
    private String SETTLEMENT_TYPE_ID_YingShouKaJi;
    @Value("${SETTLEMENT_TYPE_ID_YingShouCanPiao}")
    private String SETTLEMENT_TYPE_ID_YingShouCanPiao;
    @Value("${DICT_TYPE_ID_tuikuan}")
    private String DICT_TYPE_ID_tuikuan;
    @Value("${SETTLEMENT_TYPE_ID_jiesuan}")
    private String SETTLEMENT_TYPE_ID_jiesuan;
    @Value("${PROJECT_CODE}")
    private String PROJECT_CODE;
    @Autowired
    private ICardInfoService cardInfoService;
    @Autowired
    private ICardConsumptionRuleService cardConsumptionRuleService;
    @Autowired
    private ITradeConsumptionMainService tradeConsumptionMainService;
    @Autowired
    private IConfigMealTimeService configMealTimeService;
    @Autowired
    private ICardAccountService cardAccountService;
    @Autowired
    private ISystemPosMachineService systemPosMachineService;
    @Autowired
    private ITradeAccountConsumptionFlowService tradeAccountConsumptionFlowService;
    @Autowired
    private ITradeConsumptionDetailService tradeConsumptionDetailService;
    @Autowired
    private IMenuFoodPriceService menuFoodPriceService;
    @Autowired
    private IConfigSettlementTypeService configSettlementTypeService;
    @Autowired
    private ISystemRefundApprovalService systemRefundApprovalService;
    @Autowired
    private ICardCustomerService cardCustomerService;
    @Autowired
    private ISystemDictDataService systemDictDataService;
    @Autowired
    private ITradeAccountStoreFlowService tradeAccountStoreFlowService;
    @Autowired
    private IMemberAllowanceUseHistoryService memberAllowanceUseHistoryService;
    @Autowired
    private AutoMapper autoMapper;
    private static AlipayTradeService tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();


    /**
     * 获取可退款订单
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/consumptionFlow", method = RequestMethod.POST)
    public String consumptionFlow(Model model, HttpServletRequest request) {
        String cardCode = request.getParameter("cardCode");
        String customerName = request.getParameter("customerName");
        String customerNo = request.getParameter("customerNo");
        String physicalCode = request.getParameter("physicalCode");
        String customerId = "";
        if (cardCode.contains("&")) {
            //虚拟二维码支付
            String[] split = cardCode.split("&");
            if (split.length != 4) {
                model.addAttribute("message", "二维码无效");
                return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
            } else if (LocalDateTime.now().isAfter(LocalDateTime.parse(split[1], DateTimeFormatter.ofPattern("yyMMddHHmmss")).plusMinutes(2))) {
                model.addAttribute("message", "二维码已过期");
                return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
            } else if (split[0].equals(MD5.MD5Encode(split[3] + split[2] + split[1]).toUpperCase())) {
                //验证通过
                customerNo = split[3];
                cardCode = "";
            } else {
                model.addAttribute("message", "二维码无效");
                return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
            }
        }
        if (StringUtils.hasText(cardCode)) {
            //根据卡片编号直接查询
            CardInfo cardInfo = cardInfoService.findByCardCode(cardCode);
            if (cardInfo == null) {
                model.addAttribute("message", "该卡片未关联用户");
                return JSONObject.toJSONString(model);
            } else {
                customerId = cardInfo.getCustomerId();
            }
        } else if (StringUtils.hasText(customerNo) || StringUtils.hasText(customerName)) {
            //根据姓名,顾客编号查询
            QueryWrapper<CardCustomer> cardCustomerWrapper = new QueryWrapper<>();
            cardCustomerWrapper.eq("STATUS", 0);
            if (StringUtils.hasText(customerNo)) {
                cardCustomerWrapper.eq("CUSTOMER_NO", customerNo);
            }
            if (StringUtils.hasText(customerName)) {
                cardCustomerWrapper.eq("NAME", customerName);
            }
            CardCustomer cardCustomer = cardCustomerService.getOne(cardCustomerWrapper);
            if (cardCustomer == null) {
                model.addAttribute("message", "未查询到相关用户");
                return JSONObject.toJSONString(model);
            } else {
                customerId = cardCustomer.getId();
            }
        }
        QueryWrapper<TradeConsumptionMain> queryWrapper = new QueryWrapper<>();
        if (!"".equals(customerId)) {
            queryWrapper.eq("CUSTOMER_ID", customerId);
        }
        queryWrapper.eq("POS_MACHINE_ID", systemPosMachineService.findByPhysicalCode(physicalCode).getId());
//        queryWrapper.and(i-> i.like("REASON_ID","支付宝").or().like("REASON_ID","微信"));
        queryWrapper.orderByAsc("ORDER_STATUS");
        queryWrapper.orderByDesc("CONSUMPTION_TIME");
        queryWrapper.ge("CONSUMPTION_TIME", LocalDate.now().minusMonths(1));
        queryWrapper.and(i -> i.isNull("ORDER_STATUS").or().in("ORDER_STATUS", "1", "3"));
//        queryWrapper.eq("ORDER_STATUS","1");
        List<TradeConsumptionMain> tradeConsumptionMainList = tradeConsumptionMainService.list(queryWrapper);

        model.addAttribute("result", "success");
        model.addAttribute("mainList", tradeConsumptionMainList);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("result", "mainList", "flowNo", "consumptionTime", "reasonId", "actualAmount", "id", "orderStatus");
        return JSONObject.toJSONString(model);
    }

    /**
     * 根据主单id获取可退款细单
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "GetTradeDetailByMainId", method = RequestMethod.POST)
    public String getTradeDetailByMainId(@RequestParam("id") String id, Model model, HttpServletRequest request, HttpServletResponse response) {
        List<TradeConsumptionDetail> detailList = tradeConsumptionDetailService.query().eq("MAIN_ID", id).eq("REFUND_STATUS", "0").list();
        model.addAttribute("result", "success");
        model.addAttribute("detailList", autoMapper.mapperEntityList(detailList));
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("detailList", "result", "price", "quantity", "actualAmount", "food", "nameZh", "nameEn", "id", "mainId");
        return JSONObject.toJSONString(model, filter);
    }

    /**
     * 查询退款原因字典数据
     */
    @RequestMapping(value = "/reasonForRefund", method = RequestMethod.POST)
    public String reasonForRefund(Model model, HttpServletRequest request) {
        List<SystemDictData> systemDictDataList = systemDictDataService.query().eq("DICT_TYPE_ID", DICT_TYPE_ID_tuikuan).eq("STATUS", 1).orderByAsc("CODE").list();
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("name", "reasonList");
        model.addAttribute("reasonList", systemDictDataList);
        return JSONObject.toJSONString(model, filter);
    }


    /**
     * 生成退款审批单(部分退款)
     */
    @RequestMapping(value = "/createApproval", method = RequestMethod.POST)
    @Transactional
    public String createApproval(SystemRefundApproval systemRefundApproval, Model model) {
        model.addAttribute("result", "fail");
        if (!StringUtils.hasText(systemRefundApproval.getRefundReasons())) {
            model.addAttribute("message", "退菜原因为空，不能退菜");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        } else if (systemRefundApproval.getRefundAmount() == null || systemRefundApproval.getRefundAmount() == 0) {
            model.addAttribute("message", "退菜金额为空，不能退菜");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        List<String> detailListIds = systemRefundApproval.getDetailListIds();
        detailListIds.add(systemRefundApproval.getDetailId());
        if (detailListIds.size() <= 0) {
            model.addAttribute("message", "未选择退款菜品，不能退菜");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        List<TradeConsumptionDetail> tradeConsumptionDetails = tradeConsumptionDetailService.listByIds(detailListIds);
        //查看是否有未退款细单
        List<TradeConsumptionDetail> wtkConsumptionDetailList = tradeConsumptionDetailService.query().eq("MAIN_ID", systemRefundApproval.getMainId()).eq("REFUND_STATUS", 0).list();
        if (wtkConsumptionDetailList != null && wtkConsumptionDetailList.size() == 0) {
            TradeConsumptionMain tradeConsumptionMain = tradeConsumptionMainService.getById(systemRefundApproval.getMainId());
            tradeConsumptionMain.setOrderStatus("3");
            tradeConsumptionMainService.updateById(tradeConsumptionMain);
        }
        for (TradeConsumptionDetail tradeConsumptionDetail : tradeConsumptionDetails) {
            //修改细单退款状态
            tradeConsumptionDetail.setRefundStatus("2");
        }
        tradeConsumptionDetailService.updateBatchById(tradeConsumptionDetails);
        //查询改主单下是否有未审批审批单
        SystemRefundApproval old = systemRefundApprovalService.query().eq("MAIN_ID", systemRefundApproval.getMainId()).eq("APPROVAL_STATUS", 0).eq("REFUND_STATUS", 0).one();
        if (old != null) {
            old.setRefundAmount(old.getRefundAmount() + (systemRefundApproval.getRefundAmount()));
            old.setReason(old.getReason() + ";" + systemRefundApproval.getReason());
            old.setCreateTime(LocalDateTime.now());
            systemRefundApprovalService.updateById(old);
        } else {
            systemRefundApproval.setRefundStatus("0");
            systemRefundApproval.setApprovalStatus("0");
            systemRefundApproval.setCreateTime(LocalDateTime.now());
            systemRefundApprovalService.save(systemRefundApproval);
        }
        model.addAttribute("result", "success");
        model.addAttribute("message", "已提交退款申请，等待审批通过");
        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);

    }


    /**
     * 生成退款审批单(整单)
     */
    @RequestMapping(value = "/createApproval2", method = RequestMethod.POST)
    @Transactional
    public String createApproval2(SystemRefundApproval systemRefundApproval, Model model) {
        model.addAttribute("result", "fail");
        if (!StringUtils.hasText(systemRefundApproval.getRefundReasons())) {
            model.addAttribute("message", "退菜原因为空，不能退菜");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        } else if (systemRefundApproval.getRefundAmount() == null || systemRefundApproval.getRefundAmount() == 0) {
            model.addAttribute("message", "退菜金额为空，不能退菜");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        BigDecimal returnAmount = BigDecimal.ZERO;
        //查看是否有未退款细单
        List<TradeConsumptionDetail> wtkConsumptionDetailList = tradeConsumptionDetailService.query().eq("MAIN_ID", systemRefundApproval.getMainId()).eq("REFUND_STATUS", 0).list();

        //修改细单退款状态
        Double refundAmount = 0.0;
        for (TradeConsumptionDetail tradeConsumptionDetail : wtkConsumptionDetailList) {
            refundAmount += tradeConsumptionDetail.getActualAmount().doubleValue();
            tradeConsumptionDetail.setRefundStatus("2");//审批中
            returnAmount.add(tradeConsumptionDetail.getActualAmount());
        }
        if (refundAmount < systemRefundApproval.getRefundAmount()) {
            systemRefundApproval.setRefundAmount(refundAmount);
        }
        //修改主单状态
        TradeConsumptionMain tradeConsumptionMain = tradeConsumptionMainService.getById(systemRefundApproval.getMainId());
        tradeConsumptionMain.setOrderStatus("3");
        tradeConsumptionMainService.updateById(tradeConsumptionMain);
        tradeConsumptionDetailService.updateBatchById(wtkConsumptionDetailList);
        //查询改主单下是否有未审批审批单
        SystemRefundApproval old = systemRefundApprovalService.query().eq("MAIN_ID", systemRefundApproval.getMainId()).eq("APPROVAL_STATUS", 0).eq("REFUND_STATUS", 0).one();
        if (old != null) {
            if (returnAmount.doubleValue() == 0) {
                old.setRefundAmount(old.getRefundAmount() + (systemRefundApproval.getRefundAmount()));
            } else {
                old.setRefundAmount(old.getRefundAmount() + returnAmount.doubleValue());
            }
            old.setReason(old.getReason() + ";" + systemRefundApproval.getReason());
            old.setCreateTime(LocalDateTime.now());
            systemRefundApprovalService.updateById(old);
        } else {
            systemRefundApproval.setRefundStatus("0");
            systemRefundApproval.setApprovalStatus("0");
            systemRefundApproval.setCreateTime(LocalDateTime.now());
            systemRefundApprovalService.save(systemRefundApproval);
        }
        model.addAttribute("result", "success");
        model.addAttribute("message", "已提交退款申请，等待审批通过");
        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);

    }

    /**
     * 获取退款审批单
     */
    @RequestMapping(value = "/getApproval", method = RequestMethod.POST)
    public String getApproval(Model model, HttpServletRequest request) {
//        String canci = request.getParameter("canci");
//        ConfigMealTime configMealTime = configMealTimeService.findByName(canci);
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        QueryWrapper<SystemRefundApproval> systemRefundApprovalWrapper = new QueryWrapper<>();
//        systemRefundApprovalWrapper.eq("APPROVAL_STATUS", "0");
//        systemRefundApprovalWrapper.ne("REFUND_STATUS", "1");
        systemRefundApprovalWrapper.between("CREATE_TIME", startTime, LocalDate.parse(endTime.split("T")[0]).plusDays(1));
        systemRefundApprovalWrapper.orderByAsc("APPROVAL_STATUS");
        systemRefundApprovalWrapper.orderByDesc("CREATE_TIME");
        List<SystemRefundApproval> list = systemRefundApprovalService.list(systemRefundApprovalWrapper);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter("approvalStatus", "id", "tradeConsumptionMain", "refundAmount", "refundReasons", "refundStatus", "createTime", "reasonId");
        return JSONObject.toJSONString(list, filter);
    }


    /**
     * 通过退款审批单
     */
    @RequestMapping(value = "/passApproval", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public String passApproval(@RequestBody SystemRefundApproval systemRefundApproval, Model model, HttpServletRequest request) throws IOException {
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        systemRefundApproval = systemRefundApprovalService.getById(systemRefundApproval.getId());
        systemRefundApproval.setApprovalStatus("1");//已审批
        systemRefundApproval.setApprovalTime(LocalDateTime.now());
        systemRefundApproval.setApprovalName(user.getName());
        systemRefundApprovalService.updateById(systemRefundApproval);
        //开始退款
        Map<String, String> resultMap = null;
        if (systemRefundApproval.getTradeConsumptionMain().getReasonId().contains("微信")) {
            //微信退款
            resultMap = wRefund(systemRefundApproval, systemRefundApproval.getTradeConsumptionMain());
        } else if (systemRefundApproval.getTradeConsumptionMain().getReasonId().contains("支付宝")) {
            //支付宝退款
            resultMap = aLiTransferToReFul(systemRefundApproval, systemRefundApproval.getTradeConsumptionMain());
        } else if (systemRefundApproval.getTradeConsumptionMain().getReasonId().contains("刷卡")) {
            //刷卡退款
            systemRefundApproval.setCustomerId(systemRefundApproval.getTradeConsumptionMain().getCustomerId());
            resultMap = offset(systemRefundApproval, user);
        } else if (systemRefundApproval.getTradeConsumptionMain().getReasonId().contains("现金")) {
            resultMap = new HashMap<>();
            resultMap.put("is_success", "YES");
        }
        if (resultMap != null && "YES".equals(resultMap.get("is_success"))) {
            //修改审批单
            systemRefundApproval.setRefundStatus("1");
            systemRefundApprovalService.updateById(systemRefundApproval);
            //修改细单
            List<TradeConsumptionDetail> consumptionDetailList = tradeConsumptionDetailService.query().eq("MAIN_ID", systemRefundApproval.getMainId()).eq("REFUND_STATUS", 2).list();
            Double discountAmount = 0.0;
            for (TradeConsumptionDetail consumptionDetail : consumptionDetailList) {
                discountAmount += consumptionDetail.getHandDiscount().doubleValue();
                consumptionDetail.setRefundStatus("1");
            }
            tradeConsumptionDetailService.updateBatchById(consumptionDetailList);
            //修改主单
            TradeConsumptionMain tradeConsumptionMain = systemRefundApproval.getTradeConsumptionMain();
            //修改金额
//            tradeConsumptionMain.setActualAmount(tradeConsumptionMain.getActualAmount() - systemRefundApproval.getRefundAmount());
            //修改折扣
//            tradeConsumptionMain.setDiscountAmount(tradeConsumptionMain.getDiscountAmount() - discountAmount);
            if ("3".equals(tradeConsumptionMain.getOrderStatus())) {
                tradeConsumptionMain.setOrderStatus("2");
            }
            //删除优惠
            if (tradeConsumptionMain.getDiscountAmount() > 0) {


                memberAllowanceUseHistoryService.remove(new QueryWrapper<MemberAllowanceUseHistory>().eq("order_id", tradeConsumptionMain.getId()));
            }
            tradeConsumptionMainService.updateById(tradeConsumptionMain);
            TradeAccountConsumptionFlow tradeAccountConsumptionFlow = tradeAccountConsumptionFlowService.query()
                    .eq("FLOW_NO", tradeConsumptionMain.getFlowNo())
                    .eq("ACCOUNT_ID", tradeConsumptionMain.getAccountId())
                    .gt("ACTUAL_AMOUNT", 0).list().get(0);
            tradeAccountConsumptionFlow.setId(null);
            tradeAccountConsumptionFlow.setBeforeAmount(new BigDecimal(0));
            tradeAccountConsumptionFlow.setActualAmount(-systemRefundApproval.getRefundAmount());
            tradeAccountConsumptionFlow.setAfterAmount(new BigDecimal(0));
            tradeAccountConsumptionFlow.setDiscountAmount(0.0);
            tradeAccountConsumptionFlow.setReasonId("退款");
            tradeAccountConsumptionFlow.setIsOver("1");
            tradeAccountConsumptionFlow.setCreateTime(LocalDateTime.now());
            tradeAccountConsumptionFlowService.save(tradeAccountConsumptionFlow);
        } else {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "退款失败");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
        model.addAttribute("result", "success");
        model.addAttribute("message", "已完成审批并退款");
        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
    }

    /**
     * 驳回退款审批单
     */
    @RequestMapping(value = "/rejectApproval", method = RequestMethod.POST)
    public String rejectApproval(@RequestBody SystemRefundApproval systemRefundApproval, Model model, HttpServletRequest request) {
        SystemAclUser user = (SystemAclUser) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        //修改审批单
        systemRefundApproval = systemRefundApprovalService.getById(systemRefundApproval.getId());
        systemRefundApproval.setApprovalStatus("2");//已驳回
        systemRefundApproval.setApprovalTime(LocalDateTime.now());
        systemRefundApproval.setApprovalName(user.getName());
        systemRefundApprovalService.updateById(systemRefundApproval);
        TradeConsumptionMain tradeConsumptionMain = systemRefundApproval.getTradeConsumptionMain();
        //修改细单
        List<TradeConsumptionDetail> consumptionDetailList = tradeConsumptionDetailService.query().eq("MAIN_ID", systemRefundApproval.getMainId()).eq("REFUND_STATUS", 2).list();
//        int count = 0;
        for (TradeConsumptionDetail tradeConsumptionDetail : consumptionDetailList) {
//            count += tradeConsumptionDetail.getQuantity();
            tradeConsumptionDetail.setRefundStatus("0");
        }
        tradeConsumptionDetailService.updateBatchById(consumptionDetailList);
        //修改主单
        tradeConsumptionMain.setOrderStatus("1");
//        tradeConsumptionMain.setQuantity(tradeConsumptionMain.getQuantity() + count);
//        tradeConsumptionMain.setActualAmount(tradeConsumptionMain.getActualAmount() + systemRefundApproval.getRefundAmount());
        tradeConsumptionMainService.updateById(tradeConsumptionMain);
        model.addAttribute("result", "success");
        model.addAttribute("message", "审批已驳回");
        return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
    }


    // 微信退款
    public Map<String, String> wRefund(SystemRefundApproval listModel, TradeConsumptionMain tradeConsumptionMain) {
        System.err.println("微信退款开始=====");
        Map<String, String> map = new HashMap<>();
        HashMap<String, String> data = new HashMap<String, String>();
        String totalFee;
        String refund_fee;
        data.put("out_trade_no", tradeConsumptionMain.getFlowNo());
        data.put("out_refund_no", tradeConsumptionMain.getFlowNo());
        String parameter = listModel.getRefundAmount().toString();
        String parameter1 = listModel.getRefundAmount().toString();
        try {
            Float f = Float.parseFloat(parameter) * 100;
            Float f1 = Float.parseFloat(parameter1) * 100;

            totalFee = String.valueOf(f).substring(0, f.toString().indexOf('.'));
            refund_fee = String.valueOf(f1).substring(0, f.toString().indexOf('.'));
            data.put("total_fee", totalFee);
            data.put("refund_fee", refund_fee);
        } catch (Exception e) {
            totalFee = "0";
            refund_fee = "0";
        }
        try {
            WXPayConfigImpl config = WXPayConfigImpl.getInstance();
            System.err.println("WX--------------1");
            WXPay wxpay = new WXPay(config);
            System.err.println("WX--------------2");
            Map<String, String> microPay = wxpay.refund(data);
            System.err.println("WX----3-----microPsy" + microPay.toString());
            // 判断是否成功
            map = isSuccess(microPay, wxpay, data);
            System.err.println("map中issuccess值 ；" + map.get("is_success"));
            System.err.println("结果===============" + map);
        } catch (Exception e) {
            System.err.println("e=====" + e);
            e.printStackTrace();
            map.put("is_success", "退款失败,请稍后重试!");
        }
        return map;

    }


    // 支付宝退款
    public Map<String, String> aLiTransferToReFul(SystemRefundApproval listModel,
                                                  TradeConsumptionMain tradeConsumptionMain) {
        String refund_amount = listModel.getRefundAmount().toString();
        String out_trade_no = tradeConsumptionMain.getFlowNo();
        // 创建条码支付请求builder，设置请求参数
        AlipayTradeRefundRequestBuilder builder = new AlipayTradeRefundRequestBuilder()
                // .setAppAuthToken(appAuthToken)
                .setOutTradeNo("0000000:" + out_trade_no).setRefundAmount(refund_amount)
                // .setStoreId(storeId)
                .setRefundReason(listModel.getRefundReasons());
        // .setBody(body)
        // .setOperatorId(operatorId)
        // .setExtendParams(extendParams)
        // .setSellerId(sellerId)
        // .setGoodsDetailList(goodsDetailList)

        // 调用tradePay方法获取当面付应答
        AlipayF2FRefundResult result = tradeService.tradeRefund(builder);
        Map<String, String> map = new HashMap<>();
        switch (result.getTradeStatus()) {
            case SUCCESS:
                System.err.println("支付宝退款成功: )");
                map.put("is_success", "YES");
                map.put("transaction_id", result.getResponse().getTradeNo());
                break;
            case FAILED:
                System.err.println("支付宝退款失败!!!");
                map.put("is_success", "NO");
                break;

            case UNKNOWN:
                System.err.println("系统异常，订单状态未知!!!");
                break;
            default:
                System.err.println("不支持的交易状态，交易返回异常!!!");
                map.put("is_success", "NO");
                break;
        }
        return map;

    }

    /**
     * 消费冲账(刷卡退款)
     */
    public Map<String, String> offset(SystemRefundApproval systemRefundApproval, SystemAclUser user) {
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("is_success", "fail");
        String customerId = systemRefundApproval.getCustomerId();
        String physicalCode = systemRefundApproval.getPhysicalCode();
        String amount = systemRefundApproval.getRefundAmount().toString();
        String reason = systemRefundApproval.getTkReason();
        CardAccount cardAccount;
        if (!StringUtils.hasText(amount) || Double.parseDouble(amount) <= 0) {
            resultMap.put("message", "消费金额不能为零");
            return resultMap;
        } else if (!StringUtils.hasText(reason)) {
            resultMap.put("message", "冲账原因为空，不能冲账");
            return resultMap;
        }
        cardAccount = cardAccountService.getById(systemRefundApproval.getTradeConsumptionMain().getAccountId());
        CardInfo cardInfo = cardInfoService.query().eq("CUSTOMER_ID", customerId).eq("STATUS", 0).one();
        //先存储流水
        TradeAccountStoreFlow tradeAccountStoreFlow = new TradeAccountStoreFlow();
        SystemPosMachine systemPosMachine = systemPosMachineService.findByPhysicalCode(physicalCode);
        if (systemPosMachine != null) {
            tradeAccountStoreFlow.setPosMachineId(systemPosMachine.getId());
        }
        tradeAccountStoreFlow.setCustomerId(customerId);
        tradeAccountStoreFlow.setAccountId(cardAccount.getId());
        tradeAccountStoreFlow.setCardId(cardInfo.getId());
        tradeAccountStoreFlow.setOperateType(2);
        tradeAccountStoreFlow.setSettlementTypeId(SETTLEMENT_TYPE_ID_jiesuan);//结算
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
        tradeAccountStoreFlow.setFlowNo("STRIKEJ-" + df.format(LocalDateTime.now()) + UUID.randomUUID().toString().substring(0, 4));
        tradeAccountStoreFlow.setBeforeAmount(cardAccount.getAmount());
        tradeAccountStoreFlow.setActualAmount(new BigDecimal(amount));
        tradeAccountStoreFlow.setAfterAmount(new BigDecimal(cardAccount.getAmount().doubleValue() + Double.parseDouble(amount)));
        tradeAccountStoreFlow.setBeforeTimes(0);
        tradeAccountStoreFlow.setAfterTimes(0);
        tradeAccountStoreFlow.setTimes(0);
        tradeAccountStoreFlow.setReasonId(reason);
        tradeAccountStoreFlow.setIsPay("0");
        tradeAccountStoreFlow.setCreatorId(user.getId());
        tradeAccountStoreFlow.setCreatorName(user.getName());
        tradeAccountStoreFlow.setCreateTime(LocalDateTime.now());
        //保存
        tradeAccountStoreFlowService.save(tradeAccountStoreFlow);
        cardAccount.setAmount(tradeAccountStoreFlow.getAfterAmount());
        cardAccountService.updateById(cardAccount);
        tradeAccountStoreFlowService.updateById(tradeAccountStoreFlow);
        resultMap.put("is_success", "YES");
        resultMap.put("message", "冲账成功");
        return resultMap;
    }

    public Map<String, String> isSuccess(Map<String, String> map, WXPay wxpay, Map<String, String> data) {
        if (map.get("return_code").equals("SUCCESS")) {// 通讯成功
            if (map.get("result_code").equals("SUCCESS")) {// 交易成功
                if (map.get("trade_state") == null) {
                    map.put("is_success", "YES");
                    System.err.println("111 ===" + map.get("is_success"));
                } else if (map.get("trade_state").equals("USERPAYING")) {
                    map.put("is_success", "UNKNOWN");
                    System.err.println("222 ===" + map.get("is_success"));
                } else if (map.get("trade_state").equals("SUCCESS")) {
                    map.put("is_success", "YES");
                    System.err.println("333 ===" + map.get("is_success"));
                }
                return map;
            } else if (map.get("result_code").equals("FAIL")) {
                String errCode = map.get("err_code");// 交易不明确,查询订单
                if (errCode.equals("USERPAYING") || errCode.equals("BANKERROR") || errCode.equals("SYSTEMERROR")) {
                    map.put("is_success", "UNKNOWN");
                    System.err.println("444 ===unKnown");
                    return map;
                }
            }
            System.err.println("555 ===FAIL");
            map.put("is_success", "NO");
            return map;
        } else {
            System.err.println("支付失败，请重新扫码! 666===FAIL");
            map.put("is_success", "NO");
            return map;
        }
    }

    //增加消费主单明细单
    private void insertInto(List<ItemS> itemsList, TradeAccountConsumptionFlow tradeAccountConsumptionFlow, SystemAclUser user) {
        List<TradeConsumptionDetail> detailList = new ArrayList<>();
        TradeConsumptionMain tradeConsumptionMain = new TradeConsumptionMain();
        tradeConsumptionMain.setRestaurantId(tradeAccountConsumptionFlow.getRestaurantId());
        tradeConsumptionMain.setMealTimeId(tradeAccountConsumptionFlow.getMealTimeId());
        tradeConsumptionMain.setPosMachineId(tradeAccountConsumptionFlow.getPosMachineId());
        tradeConsumptionMain.setFlowNo(tradeAccountConsumptionFlow.getFlowNo());
        tradeConsumptionMain.setConsumptionTime(LocalDateTime.now());
        tradeConsumptionMain.setOrderType(2);
        double count = 0;
        double money = 0.0;
        for (ItemS items : itemsList) {
            count += items.getCount();
            money += items.getAmount();
        }
        tradeConsumptionMain.setQuantity(count);
        tradeConsumptionMain.setShouldPaidAmount(money);
        tradeConsumptionMain.setActualAmount(money);
        tradeConsumptionMain.setDiscountPercent(BigDecimal.ZERO);
        tradeConsumptionMain.setReasonId("退菜");
        tradeConsumptionMain.setQuotaPrice(BigDecimal.ZERO);
        tradeConsumptionMain.setTimes(0);
        tradeConsumptionMain.setIsSettlement("1");
        tradeConsumptionMain.setCreatorId(user.getId());
        tradeConsumptionMain.setCreatorName(user.getName());
        tradeConsumptionMain.setCreateTime(LocalDateTime.now());
        for (ItemS itemS : itemsList) {
            TradeConsumptionDetail tradeConsumptionDetail = new TradeConsumptionDetail();
            tradeConsumptionDetail.setQuantity((double) itemS.getCount());
            tradeConsumptionDetail.setHandDiscount(BigDecimal.ZERO);
            tradeConsumptionDetail.setReasonId("");
            tradeConsumptionDetail.setActualAmount(new BigDecimal(itemS.getCount() * itemS.getPrice()));
            tradeConsumptionDetail.setMainId(tradeConsumptionMain.getId());
            tradeConsumptionDetail.setPrice(new BigDecimal(itemS.getPrice()));
            QueryWrapper<MenuFoodPrice> menuFoodPriceWrapper = new QueryWrapper<>();
            menuFoodPriceWrapper.eq("MEAL_TIME_ID", tradeAccountConsumptionFlow.getMealTimeId());
            menuFoodPriceWrapper.eq("id", itemS.getIds());
            MenuFoodPrice menuFoodPrice = menuFoodPriceService.getOne(menuFoodPriceWrapper);
            if (menuFoodPrice != null) {
                tradeConsumptionDetail.setBusinessTypeId(menuFoodPrice.getBusinessTypeId());
                tradeConsumptionDetail.setFoodId(menuFoodPrice.getFoodId());
            }
            detailList.add(tradeConsumptionDetail);
        }
        tradeConsumptionMainService.save(tradeConsumptionMain);
        tradeConsumptionDetailService.saveBatch(detailList);
    }
}
